<template>
  <div class="app-container table-app-container">
    <div class="fixed-table-actionbar">
      <div class="search-bar">
        <el-form :model="formItem" :inline="true" class="form-filter" size="mini">
          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="doBind(selections)">绑定</el-button>
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="calback">返回</el-button>
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="formItem.s_globalSearch"
              placeholder="请输入查询内容..."
              clearable
              @keyup.enter.native="init"
              @change="onGlobeSearchInputChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button plain icon="el-icon-search" @click="init" />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="fixed-table">
      <PageableTable
        :loading="loading"
        :columns="insideColumns"
        :data="insideTableData"
        :total="totalElements"
        :page="currentPage"
        :page-size="pageSize"
        :table-height="tableHeight"
        :multiple-selected="true"
        :disable-pageable="false"
        class="fixed-table-table"
        @page-change="onPageChange"
        @sort-change="onSortChange"
        @selection-change="onSelectionChange"
      >
        <template v-for="column in insideColumns">
          <el-table-column v-if="column.display" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable" :fixed="column.fixed">
            <template slot-scope="scope">
              <column-render :render="column.render" :row="scope.row" :column="column" />
            </template>
          </el-table-column>
        </template>
      </PageableTable>
    </div>
  </div>
</template>

<script>
import PageableTable from '@neu/biz-core/components/PageableTable'
import { clone } from '@neu/biz-core/utils/utils'
import { pageNoBind, saveBind, remove, batchRemove } from '@neu/dcam-ui/api/fixedAsset'
import databind from '@neu/biz-core/mixins/databind'
import { formatDate } from '@neu/biz-core/utils/utils'
import belongs from '@neu/dcam-ui/mixins/belongs'
import { ASSET_STATUS as assetStatus } from '@neu/dcam-ui/utils/constants'
import { isArray } from '@neu/biz-core/utils/utils'
/** 全局检索key */
const formItem = {
  s_belongs: '',
  s_locked: null,
  s_categories: '',
  s_globalSearch: '',
  // 管理部门查询
  s_managementOrgCode: null,
  // 小类型
  s_smallTypeCode: null,
  // 大类型
  s_bigTypeCode: null,
  // 中类型
  s_middleTypeCode: null,
  // 资产状态
  s_status: null
  // 操作员所属的部门及子部门
  // s_operatorOrgCode: null
}
export default {
  name: 'BindPage',
  components: {
    PageableTable
  },
  // 加入混入
  mixins: [databind, belongs],
  props: {
  },
  data() {
    return {
      r: pageNoBind,
      d: remove,
      ds: batchRemove,
      formItem: clone(formItem),
      insideColumns: [
        { title: '绑定状态', width: 100, key: '', display: true,
          render: (h, params) => {
            return h('span', '未绑定')
          }
        },
        { title: '原始编号', width: 100, key: 'originalCode', sortable: 'custom', display: true },
        { title: '资产名称', width: 140, key: 'name', sortable: 'custom', display: true
          // render: (h, params) => { // 查看功能
          //   if (!this.forSelection) {
          //     return h('span', [
          //       h('el-link', {
          //         class: 'font-12',
          //         attrs: { title: params.row.name },
          //         props: { type: 'primary' },
          //         on: { click: () => { this.view(params.row) } }},
          //       params.row.name)
          //     ])
          //   } else {
          //     return h('span', params.row.name)
          //   }
          // }
        },
        { title: '资产编号', width: 140, key: 'code', sortable: 'custom', display: true
          // render: (h, params) => { // 查看功能
          //   if (!this.forSelection) {
          //     return h('span', [
          //       h('el-link', {
          //         class: 'font-12',
          //         attrs: { title: params.row.code },
          //         props: { type: 'primary' },
          //         on: { click: () => { this.view(params.row) } }},
          //       params.row.code)
          //     ])
          //   } else {
          //     return h('span', params.row.code)
          //   }
          // }
        },
        { title: '资产卡片', width: 100, key: 'card', sortable: 'custom', display: false },
        { title: '大分类', width: 100, key: 'bigTypeName', sortable: 'custom', display: true },
        { title: '中分类', width: 100, key: 'middleTypeName', sortable: 'custom', display: true },
        { title: '小分类', width: 100, key: 'smallTypeName', sortable: 'custom', display: true },
        { title: '购置日期', width: 100, key: 'purchaseDate', sortable: 'custom', render: (h, params) => { return h('span', formatDate(params.row.purchaseDate, 'YYYY-MM-DD')) }, display: true },
        { title: '资产状态', width: 100, key: 'status', sortable: 'custom', display: true,
          render: (h, params) => {
            let status = ''
            const one = assetStatus.find(l => l.code === params.row.status)
            if (one) {
              status = one.name
            }
            return h('span', status)
          }
        },
        { title: '供应商', width: 100, key: 'supplierName', sortable: 'custom', display: true },
        { title: '品牌', width: 100, key: 'brand', sortable: 'custom', display: true },
        { title: '规格型号', width: 100, key: 'specifications', sortable: 'custom', display: true },
        { title: '序列号', width: 100, key: 'serialnumber', sortable: 'custom', display: true },
        { title: '机房', width: 100, key: 'computerRoom', sortable: 'custom', display: true },
        { title: '机柜', width: 100, key: 'cabinet', sortable: 'custom', display: true },
        { title: '位置', width: 150, key: 'locationName', sortable: 'custom', display: true,
          render: (h, params) => {
            let locationName = '-'
            if (params.row.location) {
              const trees = this.findParent(params.row.location, this.allLocations)
              if (trees) {
                const names = trees.map(l => l.name)
                locationName = names.join('/')
              }
            }
            return h('span', locationName)
          }
        },
        { title: '维保开始', width: 150, key: 'maintenanceStartTime', render: (h, params) => { return h('span', formatDate(params.row.maintenanceStartTime, 'YYYY-MM-DD')) }, display: true },
        { title: '维保结束', width: 150, key: 'maintenanceEndTime', render: (h, params) => { return h('span', formatDate(params.row.maintenanceEndTime, 'YYYY-MM-DD')) }, display: true },
        { title: '合同', width: 100, key: 'contractNo', sortable: 'custom', display: true },
        { title: '计量单位', width: 100, key: 'measureUnit', sortable: 'custom', display: true },
        { title: '数量', width: 100, key: 'amount', sortable: 'custom', display: true },
        { title: '金额', width: 100, key: 'money', sortable: 'custom', display: true },
        { title: '使用期限', width: 100, key: 'usePeriod', sortable: 'custom', display: true },
        { title: '使用部门', width: 150, key: 'managementOrgName', sortable: 'custom', display: true },
        { title: '使用人', width: 100, key: 'managementUserName', sortable: 'custom', display: true },
        { title: '用途', key: 'purpose', display: true },
        { title: '备注', key: 'note', display: true }
      ],
      searchObj: {
        s_belongs: ''
      },
      bindObj: {
        s_bindCode: ''
      },
      allLocations: []
    }
  },
  created() {
    this.$store.dispatch('dcam/setAssetSearchObj', {})
    this.init()
  },
  methods: {
    clearForm() {
      this.formItem = clone(formItem)
    },
    reset() {
      this.formItem = clone(formItem)
      this.init()
    },
    onGlobeSearchInputChange(value) {
      if (value === '') {
        this.init()
      }
    },
    init() {
      // if (this.statusCode) {
      //   this.searchObj['s_statusCode'] = this.statusCode
      // }
      if (this.status) {
        this.searchObj['s_status'] = this.status
      }
      if (this.locked != null) {
        this.searchObj['s_locked'] = this.locked
      }
      if (this.smallTypeCode != null) {
        this.searchObj['s_smallTypeCode'] = this.smallTypeCode
      }
      if (this.specifications != null) {
        this.searchObj['s_specifications'] = this.specifications
      }
      if (this.$attrs['management-org-code']) {
        this.searchObj['s_managementOrgCode'] = this.$attrs['management-org-code']
      }
      if (this.$attrs['location-arr']) {
        this.searchObj['s_locationArr'] = this.$attrs['location-arr'].join(',')
      }
      if (this.$attrs['type-arr']) {
        this.searchObj['s_typeCodesArr'] = this.$attrs['type-arr'].join(',')
      }
      // if (this.formItem.s_globalSearch) {
      this.searchObj['s_globalSearch'] = this.formItem.s_globalSearch
      // }
      this.searchObj.s_belongs = this.belongs
      this.searchObj.s_categories = this.categories
      // 配件查询的参数 机器设备-其他计算机设备-机器配件
      this.searchObj['s_bindCode'] = this.$attrs.asset.code
      this.searchObj['s_bindName'] = this.$attrs.asset.name
      this.searchObj['s_smallTypeCode'] = '1190299010000'
      this.searchObj['s_smallTypeName'] = '机器配件'
      this.searchObj['s_middleTypeCode'] = '1190299000000'
      this.searchObj['s_middleTypeName'] = '其他计算机设备'
      this.searchObj['s_bigTypeCode'] = '1190200000000'
      this.searchObj['s_bigTypeName'] = '机器设备'
      this.searchObj['s_statusCode'] = 'used,unused'
      this.filter(this.searchObj)

      let hiddenColumns = []
      if (this.categories === '3') {
        hiddenColumns = ['bigTypeName', 'middleTypeName', 'originalCode', 'supplierName', 'code', 'card', 'serialnumber', 'computerRoom', 'cabinet', 'location', 'maintenanceStartTime', 'maintenanceEndTime', 'contractNo', 'usePeriod', 'managementOrgName', 'managementUserName', 'purchaseDate', 'status', 'brand', 'specifications', 'locationName', 'money']
      } else {
        if (this.belongs === 'sl') {
          hiddenColumns = ['computerRoom', 'cabinet', 'amount']
        } else {
          hiddenColumns = ['card', 'amount']
        }
      }
      this.insideColumns = this.insideColumns.filter(e => !hiddenColumns.includes(e.key))

      const originalCodeColumn = this.insideColumns.find(it => it.key === 'originalCode')
      if (originalCodeColumn) {
        if (this.belongs === 'kj') {
          originalCodeColumn.title = '原始编码'
        } else if (this.belongs === 'sl') {
          originalCodeColumn.title = '资产卡片'
        }
      }
    },
    calback() {
      this.$emit('cancel')
      // 返回时查询已绑定的机器设备
      this.$emit('load', this.searchObj)
    },
    findParent(item, flattenTree) {
      const parentArr = [] // 存储所有的父级元素
      function find(item, flattenTree) {
        flattenTree.forEach(ele => {
          if (ele.code === item) {
            parentArr.unshift({ code: ele.code, name: ele.title })
            find(ele.parentKey, flattenTree)
          }
        })
      }
      find(item, flattenTree)
      return parentArr
    },
    // 机器配件绑定
    doBind(selections) {
      if (isArray(selections)) {
        if (selections.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择要绑定的记录'
          })
          return
        }
        const selectStr = selections.map(item => item.code + '-' + item.name).join('_')
        this.bindObj.s_bindCode = this.$attrs.asset.code
        this.bindObj.s_bindName = this.$attrs.asset.name
        this.bindObj.s_selectStr = selectStr
        saveBind(this.bindObj).then(response => {
          if (response === false) return
          this.$message({
            showClose: true,
            message: '绑定成功',
            type: 'success'
          })
          // 更新表格
          this.calback()
        })
      }
    }
  }
}
</script>
